package com.jn.singleton.type7;

/**
 * 静态内部类
 *
 * @author 江南大学1033190417
 * @date 2022/4/10 15:59
 */
public class SingletonTest3 {
    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        Singleton instance1 = Singleton.getInstance();
        System.out.println(instance1 == instance);//true
        System.out.println(instance.hashCode());
        System.out.println(instance1.hashCode());//相同
    }
}

//静态内部类
//推荐使用
class Singleton {

    private static volatile Singleton instance;

    private Singleton() {
    }

    //静态内部类,里面有一个属性Singleton
    /*
       1.外部类Singleton被装载时，静态内部类不会被立即装载
       2.当调用getInstance()时，静态内部类才会被装载，而且值装载一次，不会引发线程安全问题
     */
    private static class SingleInstance{
        private static final Singleton INSTANCE=new Singleton();
    }

    public static Singleton getInstance() {
        return SingleInstance.INSTANCE;
    }

}
